import React, { useRef } from "react";
type PropsType = {
  children: JSX.Element;
  upload?: (file: File) => void;
  beforeUpload?: (file: File) => boolean;
};
export const Upload: React.FC<PropsType> = ({
  children,
  upload,
  beforeUpload,
}) => {
  const input = useRef<HTMLInputElement | null>(null);
  const handleClick = () => {
    input.current?.click();
  };
  const handleChange = () => {
    if (input.current && input.current.files) {
      const file = input.current.files[0];
      if (file) {
        const isUpload = beforeUpload ? beforeUpload(file) : true;
        isUpload && upload && upload(file);
      }
    }
  };
  return (
    <div onClick={() => handleClick()} style={{ display: "inline-block" }}>
      <input
        ref={input}
        type="file"
        style={{ display: "none" }}
        onChange={handleChange}
      />
      {children}
    </div>
  );
};
